<template>
    <div class="content">
        <el-form class="form">
            <el-form-item label="产品类型">
                <el-select v-model="searchParams.fundType" size="mini" class="item" clearable filterable>
                    <el-option v-for="(value, key) in fundTypeOptions" :key="key" :value="key" :label="value"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="产品信息">
                <RiskEntryInput
                    :url="'/ledger/fundInfo/list/byUser/like?fundCodeOrName='"
                    @set-entry-data="getEntryslist"
                    :itemKey="'fundProductCode'"
                    :returnDatas="searchParams.codeAndName"
                    class="item"
                    style="display: inline-block"
                />
            </el-form-item>
            <el-form-item label="状态">
                <el-select v-model="searchParams.status" size="mini" class="item" clearable>
                    <el-option v-for="(value, key) in statusOptions" :key="key" :value="key" :label="value"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="合同类型">
                <el-select v-model="searchParams.contractType" size="mini" class="item" filterable clearable>
                    <el-option v-for="(value, key) in contractTypeOptions" :key="key" :value="key" :label="value"></el-option>
                </el-select>
            </el-form-item>
            <el-form-item label="合同上传日期">
                <el-date-picker
                    v-model="searchParams.uploadDate"
                    value-format="yyyyMM"
                    type="month"
                    class="item"
                    placeholder="选择日期"
                    size="mini"
                    clearable
                >
                </el-date-picker>
            </el-form-item>
            <el-form-item label-width="0px">
                <el-button size="mini" type="primary" @click="handleBtn('search')">查询</el-button>
                <el-button size="mini" type="primary" @click="handleBtn('loadout')">导出</el-button>
            </el-form-item>
        </el-form>
        <RiskTableP
            ref="risk-table"
            :tableConfig="tableConfig"
            :tableData="tableData"
            :column="tableColumns"
            :paging="paging"
            v-loading="tableLoading"
            @page-change="getTableData"
            style="height: calc(100% - 60px)"
        >
            <template #contractName="{ row }">
                <span class="cell-contractName" @click="downLoadByContract(row)">{{ row.contractName ? `【${row.contractName}】` : '--' }}</span>
            </template>
        </RiskTableP>
    </div>
</template>
<script lang="ts">
import RiskEntryInput from '@/common/components/risk-entry-input.vue';
import RiskTableP from '@/common/components/risk-table-plus.vue';
import { PageVO, TableConfigVO } from '@/common/vo';
import { downLoadFile } from '@/utils/request';
import { Component, Prop, Vue, Watch } from 'vue-property-decorator';
import * as api from '../api/fund-pending-manage';
import DictionConstUtil from '../dict';
import JSEncrypt from 'jsencrypt';
import moment from 'moment';
import { dateFormat } from '@/utils/tools';

@Component({ name: 'ContractDetail', components: { RiskTableP, RiskEntryInput } })
export default class ContractDetail extends Vue {
    fundTypeOptions = DictionConstUtil.fundTypeOptions;
    statusOptions = DictionConstUtil.statusOptions;
    contractTypeOptions = DictionConstUtil.contractTypeOptions;
    @Prop() echartParams: any;
    searchParams: any = {
        fundType: '',
        codeAndName: '',
        status: '',
        contractType: '',
        uploadDate: '',
    };
    tableLoading: boolean = true;
    tableConfig: TableConfigVO = {
        rowKey: 'serialNo', // 主键key
        allRowKeys: [], // 所有页数据的key集合
    };
    tableData: any[] = [];
    tableColumns = [
        {
            type: 'checkbox',
            selectedAll: false,
            fixed: 'left',
            align: 'center',
            width: 60,
        },
        {
            title: '序号',
            field: 'serialNo',
            minWidth: 100,
        },
        {
            title: '合同状态',
            field: 'status',
            minWidth: 100,
            align: 'center',
            render: value => this.statusOptions[value],
        },
        {
            title: '合同类型',
            field: 'contractType',
            minWidth: 100,
            align: 'center',
            render: value => this.contractTypeOptions[value],
        },
        {
            title: '产品编号',
            field: 'fundCode',
            minWidth: 100,
        },
        {
            title: '产品简称',
            field: 'fundNameSt',
            minWidth: 200,
        },
        {
            title: '产品类型',
            field: 'fundType',
            minWidth: 100,
            render: value => value && value.join(','),
            align: 'center',
        },
        {
            title: '合同信息',
            field: 'contractName',
            minWidth: 200,
            align: 'center',
            // 点击时需要支持下载
        },
        {
            title: '合同上传日期',
            field: 'uploadDate',
            minWidth: 120,
            align: 'center',
            render: value => dateFormat(value),
        },
        {
            title: '变更人',
            field: 'sponsor',
            minWidth: 100,
        },
        {
            title: '变更日期',
            field: 'takeEffectDate',
            minWidth: 140,
            align: 'center',
            render: value => (!value || value == '0' ? '' : moment(value, 'YYYYMMDDHHmmss').format('YYYY-MM-DD HH:mm:ss')),
        },
    ];

    paging: PageVO = {
        currentPage: 1,
        pageSize: 25,
        total: 0,
    };

    rsaPassWord: any = null;
    @Prop() activeValue: string;
    isFirst: boolean = true;
    @Watch('activeValue', { immediate: true })
    handleActiveValue() {
        if (this.activeValue === 'contract-detail') {
            if (this.isFirst) {
                if (this.echartParams.isClick) {
                    this.getTableData();
                }
                var encryptor = new JSEncrypt(); // 创建加密对象实例
                // 之前ssl生成的公钥，复制的时候要小心不要有空格
                var pubKey =
                    'MIGfMA0GCSqGSIb3DQEBAQUAA4GNADCBiQKBgQDI1/pR72vGeQoQ8YxKVrDzV6RriOkNkW0UWw4JgXhH417lULhKMQWK3GeJW+Tg0kHlhpx4iQNxrEPlroCqZfylgPI+x0AohcnvkY52VGQGLnms2tMefBKdz2BHUAp7MdF7GsGtpiHWSZbEWk5onkB7pH8Q0KlNAB+7BoNTj9MOywIDAQAB';
                encryptor.setPublicKey(pubKey); // 设置公钥
                this.rsaPassWord = encryptor.encrypt('zszg@zgssfkxt'); // 对内容进行加密
            }
            this.isFirst = false;
            // else {
            //     this.searchParams.contractType = '';
            // }
        }
    }

    @Watch('echartParams', { deep: true })
    handleEchartParams() {
        if (this.activeValue === 'contract-detail' && !this.echartParams.isClick) {
            this.searchParams = {
                fundType: '',
                codeAndName: '',
                status: '',
                contractType: this.echartParams.params['contractType'],
                uploadDate: this.echartParams.params['xValue'],
            };
            this.getTableData();
        }
    }

    /**
     * 表格数据
     */
    getTableData(type?: string) {
        this.tableLoading = true;
        api.contractDetail({ ...this.searchParams, paging: this.paging })
            .then((res: any) => {
                this.tableData = res?.list || [];
                this.paging.total = res?.total || 0;
            })
            .catch(err => {
                console.log(err, 'contractDetail');
            })
            .finally(() => {
                this.tableLoading = false;
            });
    }

    /**
     * 按钮点击
     */
    async handleBtn(type: string) {
        if (type == 'search') {
            this.paging.currentPage = 1;
            this.getTableData('search');
            this.$nextTick(() => {
                (this.$refs['risk-table'] as any).resetCheckRowKeys();
            });
        } else if (type == 'loadout') {
            const checkRowKeys = (this.$refs as any)['risk-table'].checkRowKeys || [];
            await downLoadFile({
                url: '/agent/task/contract/export',
                method: 'post',
                data: checkRowKeys.length ? { serialNo: checkRowKeys } : this.searchParams,
            });
            this.$nextTick(() => {
                (this.$refs['risk-table'] as any).resetCheckRowKeys();
            });
        }
    }

    /**
     * 合同下载
     */
    downLoadByContract(row: any) {
        // api.contractDownload({
        //     fileId: [row.contractFileId],
        //     passWord: this.rsaPassWord,
        // }).then((res: any) => {});
        downLoadFile({
            url: '/apiAssetFile/productDownLoad',
            method: 'post',
            data: { fileId: [row.contractFileId], fileName: row.contractName, passWord: this.rsaPassWord },
        });
    }

    // 产品代码
    getEntryslist(val: any) {
        this.searchParams.codeAndName = val;
    }
}
</script>
<style lang="scss" scoped>
.content {
    .form {
        display: grid;
        grid-template-columns: repeat(4, 4fr) 6fr 5fr;
        border: 1px solid #ccc;
        padding: 8px;
        margin-bottom: 10px;
        .el-form-item {
            margin-bottom: 0px;
        }
        .item {
            width: 60%;
        }
    }
}

.cell-contractName {
    cursor: pointer;
    &:hover {
        color: #409eff;
    }
}
</style>
